/*
 * Sesame Inc.
 * Copyright (c) 2009 All Rights Reserved.
 */
package com.sesame.controller.admin;

import java.util.*;

import javax.servlet.http.*;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.sesame.domain.Album;
import com.sesame.domain.Image;
import com.sesame.domain.User;
import com.sesame.service.AlbumService;
import com.sesame.service.SearchService;

/**
 * @author voidman
 * 
 */
public class AdminSearchController extends AbstractController {
    private SearchService searchService;

    public void setSearchService(SearchService searchService) {
        this.searchService = searchService;
    }

    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        if ("admin".equals(request.getSession().getAttribute("adminRank"))) {
            String q = request.getParameter("q");
            String type = request.getParameter("type");

            if (q == null) {
                return new ModelAndView("admin/adminSearch");

            } else {
                long start_time = System.currentTimeMillis();
                List<Object> objectList = searchService.search(q, type);
                long cost_time = System.currentTimeMillis() - start_time;
                float cost = cost_time / 1000f;
                Map model = new HashMap();
                if (type.equals("user")) {
                    List<User> userList = new ArrayList<User>();
                    for (int i = 0; i < objectList.size(); i++) {
                        userList.add((User) objectList.get(i));
                    }
                    model.put("userList", userList);
                } else if (type.equals("album")) {
                    List<Album> albumList = new ArrayList<Album>();
                    for (int i = 0; i < objectList.size(); i++) {
                        albumList.add((Album) objectList.get(i));
                    }
                    model.put("albumList", albumList);
                } else if (type.equals("image")) {
                    List<Image> imageList = new ArrayList<Image>();
                    for (int i = 0; i < objectList.size(); i++) {
                        imageList.add((Image) objectList.get(i));
                    }
                    model.put("imageList", imageList);
                } else {

                }

                model.put("q", q);
                model.put("type", type);
                model.put("do", "done");

                model.put("time", String.valueOf(cost));
                return new ModelAndView("admin/adminSearch", model);
            }
        } else {
            return new ModelAndView("redirect:adminError.html");
        }

    }

}